﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPlacement : MonoBehaviour {
    public Transform target;
    public bool isRetainTarget;

    // target是否居中安放（默认放置在碰撞点位置）
    public bool isCenter;

    // target插入当前物体的深度（0表示不插入，即位于物体表面；0.5表示目标自身的一半插入到物体中）
    [Range(0.0f, 0.5f)]
    public float insertPercentage = 0.0f;

    Transform _t;

    void Start() {
        _t = transform;
    }

    void Update() {
        if (target == null) {
            return;
        }

        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit)) {
                // 由于美术提供的模型资源都是Z轴朝上，故用forward属性来进行竖直方向的判定
                // 注：美术提供的模型坐标位于模型底部中心位置
                if (isCenter) {
                    var height = _t.GetComponent<MeshRenderer>().bounds.size.y;
                    target.position = _t.position + (_t.forward * height);
                    target.forward = _t.forward;
                } else {
                    target.position = hit.point;
                    target.forward = hit.normal;              
                }

                var targetHeight = target.GetComponent<MeshRenderer>().bounds.size.y;
                target.position -= (target.forward * targetHeight * insertPercentage);
            }
        }

        if (isRetainTarget == false) {
            target = null;
        }
    }
}
